package mybatis.executor;

import mybatis.config.Configuration;
import mybatis.mapper.MapperStatement;

import java.sql.*;
import java.util.List;
import java.util.Map;

/**
 * @author cg
 * @date 2023/6/20 13:36
 */
public class DefaultExecutor implements Executor {
    private static Connection connection;
    static {
        //初始化数据库连接
        initConnection();
    }
    @Override
    public <E> List<E> query(MapperStatement mapperStatement, Map<String, Object> parameters) {
        try {
            //获取数据库连接
            Connection connection = getConnection();
            StatementHandler statementHandler = new StatementHandler(mapperStatement);
            //解析mapper
            PreparedStatement preparedStatement = statementHandler.resolve(connection,parameters);
            //替换?参数
            statementHandler.injectParameters(preparedStatement, parameters);
            //执行sql语句
            ResultSet resultSet = preparedStatement.executeQuery();

            //处理结果
            ResultSetHandler resultSetHandler = new ResultSetHandler(mapperStatement);
            return resultSetHandler.handle(resultSet);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Integer update(MapperStatement mapperStatement, Map<String, Object> parameters) {
        try {
            //获取数据库连接
            Connection connection = getConnection();
            StatementHandler statementHandler = new StatementHandler(mapperStatement);
            //解析mapper
            PreparedStatement preparedStatement = statementHandler.resolve(connection, parameters);
            //替换?参数
            statementHandler.injectParameters(preparedStatement, parameters);
            //执行sql语句
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() {
        return connection;
    }
    //初始化数据库连接
    private static void initConnection() {
        //数据库驱动
        String driver = Configuration.getProperties().getProperty("db.driver");
        //数据库地址
        String url = Configuration.getProperties().getProperty("db.url");
        String username = Configuration.getProperties().getProperty("db.username");
        String password = Configuration.getProperties().getProperty("db.password");
        try
        {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("数据库连接成功");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}
